package com.elitesland.system.rest;

import com.elitesland.core.base.ApiCode;
import com.elitesland.core.base.ApiResult;
import com.elitesland.core.base.PagingVO;
import com.elitesland.system.param.SysNumberReqParam;
import com.elitesland.system.param.SysNumberRuleQParam;
import com.elitesland.system.service.SysNumberRuleService;
import com.elitesland.system.vo.SysNumberRuleVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <pre></pre>
 *
 * @author mir
 * @date 2020-10-11
 */
@RestController
@RequestMapping("/sys/numbering")
@Api(value = "发号器规则管理", tags = {"发号器API"})
public class SysNumberRuleController {

    private SysNumberRuleService sysNumberRuleService;

    @Autowired
    public void setSysNumberRuleService(SysNumberRuleService sysNumberRuleService) {
        this.sysNumberRuleService = sysNumberRuleService;
    }

    @PostMapping("/samplecode")
    @ApiOperation("生成样例号码")
    public ApiResult<String> getSampleCode(@RequestBody SysNumberReqParam param) {
        val code = sysNumberRuleService.generateSampleCode(param.getRuleId(), param.getRuntimeValue());
        return ApiResult.ok(code);
    }

    @PostMapping("/code")
    @ApiOperation("生成号码")
    public ApiResult<String> getCode(@RequestBody SysNumberReqParam param) {
        val code = sysNumberRuleService.generateCode(param.getRuleId(), param.getRuntimeValue());
        return ApiResult.ok(code);
    }

    @PostMapping("/q")
    @ApiOperation("检索发号器规则")
    public ApiResult<PagingVO<SysNumberRuleVO>> search(@RequestBody SysNumberRuleQParam param) {
        val rules = sysNumberRuleService.search(param);
        return ApiResult.ok(rules);
    }

    @GetMapping("/rules/{id}")
    @ApiOperation("根据规则ID，获取规则对象，包括规则明细列表")
    public ApiResult<SysNumberRuleVO> one(@PathVariable Long id) {
        return sysNumberRuleService.oneCombined(id).map(ApiResult::ok)
                .orElse(ApiResult.fail(ApiCode.NOT_FOUND));
    }

    @PostMapping("/rules")
    @ApiOperation("创建发号器规则，成功则返回对应ID")
    public ApiResult<String> create(@RequestBody SysNumberRuleVO rule) {
        val id = sysNumberRuleService.create(rule);
        return ApiResult.ok(String.valueOf(id));
    }

    @PutMapping("/rules")
    @ApiOperation("更新发号器规则")
    public ApiResult<Object> update(@RequestBody SysNumberRuleVO rule) {
        sysNumberRuleService.update(rule);
        return ApiResult.ok();
    }

    @DeleteMapping("/rules/{id}")
    @ApiOperation("删除发号器规则，及对应规则明细")
    public ApiResult<Object> remove(@PathVariable Long id) {
        sysNumberRuleService.removeById(id);
        return ApiResult.ok();
    }
}
